<?php

class SearchController extends DefaultBaseController 
{

    public function indexAction()
    {
    	$this->view->indexCountries = Obj_Country::getCountries(true);
    	
    	$phrase = trim($this->getRequest()->getParam('phrase', ''));
    	if ($phrase != '') {
    		if (strlen($phrase) < 4) {
    			throw new Exception(_('Слишком короткий запрос'), 101);
    		}
    		$ar = Obj_System_SearchIndex::search($phrase);
    		$this->_helper->viewRenderer->setRender('search-results');
    		$this->view->objects = $this->prepareSearchResults($ar);
    		$this->view->restitle = _('Результаты поиска для `'.$phrase.'`');
    		$this->view->phrase = $phrase;
    		return;
    	}
    	
    	
    	$this->view->{'SIGN_'.CURRENCY_TYPE_DOLLAR} = '$%';
    	$this->view->{'SIGN_'.CURRENCY_TYPE_EURO} = '&euro; %';
    	$this->view->{'SIGN_'.CURRENCY_TYPE_RU} = '% '.$this->view->translate('руб.');
    	
    	
    	
    	
    	if (Zend_Registry::isRegistered('parsedParams')) {
    		//url access
    		$parsedParams = Zend_Registry::get('parsedParams');
    		if (isset($parsedParams[4])) {
    			$this->showObject($parsedParams);
    			return;
    		}
    		if (!($country = $this->loadCountryLayoutInfo($parsedParams[0]))) {
    			throw new Exception(_('Страница не существует'), 101);
    		}
    		if (sizeof($parsedParams) == 1) {
    			$arRegions = Obj_Region::getRegions($country['ID'], true);
    			$this->view->children = $arRegions;
    			$this->view->childrenLink = HTTP_HOST.'/'.$country['alias'].'/';
    			$this->view->childrenName = _('Регионы');
    			Obj_Search::setBoxParam('country', $country['ID']);
    			$arPages = Obj_LocationContentPage::getLocationContentPages($country['ID'], CONTENT_TYPE_COUNTRY);
				if (trim($country['CatalogPDF']) != '')	$arPages[] = array('href' => HTTP_HOST.'/data/'.$country['CatalogPDF'], 'title' => _('Скачать каталог недвижимости'), 'target' => '_blank');
    			$this->view->pages = $arPages;
    			$this->view->restitle = $country['Name'];
    			$this->view->pageText = stripslashes($country['pageText']);
    		}
    		elseif (sizeof($parsedParams) == 2) {
    			if (!($region = Obj_Region::findRegion(urldecode($parsedParams[1])))) {
    				throw new Exception(_('Страница не существует'), 101);
    			}
    			Zend_Registry::set('LastModified', $region['Modified']);
    			$arCities = Obj_City::getCities($region['ID'], true);
    			$this->view->children = $arCities;
    			$this->view->childrenLink = HTTP_HOST.'/'.$country['alias'].'/'.$region['alias'].'/';
    			$this->view->childrenName = _('Города региона');
    			Obj_Search::setBoxParam('country', $country['ID']);
    			Obj_Search::setBoxParam('region', $region['ID']);
				Zend_Registry::set('metainfo', array(
					'title' => $region['seoTitle'],
					'description' => $region['seoDescription'],
					'keywords' => $region['seoKeywords'],
				));
				$this->view->restitle = $region['Name'];
    		}
    		elseif (sizeof($parsedParams) == 3) {
    			if ($parsedParams[1] == 'info') {
	    			$arRegions = Obj_Region::getRegions($country['ID'], true);
	    			$this->view->children = $arRegions;
	    			$this->view->childrenLink = HTTP_HOST.'/'.$country['alias'].'/';
	    			$this->view->childrenName = _('Регионы');
    				Obj_Search::setBoxParam('country', $country['ID']);
    				$this->showCountryPage($country['ID'], $parsedParams[2]);
	    			$arPages = Obj_LocationContentPage::getLocationContentPages($country['ID'], CONTENT_TYPE_COUNTRY);
	    			if (trim($country['CatalogPDF']) != '')	$arPages[] = array('href' => HTTP_HOST.'/data/'.$country['CatalogPDF'], 'title' => _('Скачать каталог недвижимости'), 'target' => '_blank');
	    			$this->view->pages = $arPages;
    				return;
    			}
    			if (!($region = Obj_Region::findRegion(urldecode($parsedParams[1])))) {
    				throw new Exception(_('Страница не существует'), 101);
    			}
    			if (!($city = Obj_City::findCity(urldecode($parsedParams[2])))) {
    				throw new Exception(_('Страница не существует'), 101);
    			}
    			Zend_Registry::set('LastModified', $city['Modified']);
    			$arLocations = Obj_Location::getLocations($city['ID'], true);
    			$this->view->children = $arLocations;
    			$this->view->childrenLink = HTTP_HOST.'/'.$country['alias'].'/'.$region['alias'].'/'.$city['alias'].'/';
    			$this->view->childrenName = _('Районы города');
    			Obj_Search::setBoxParam('country', $country['ID']);
    			Obj_Search::setBoxParam('region', $region['ID']);
    			Obj_Search::setBoxParam('city', $city['ID']);
				Zend_Registry::set('metainfo', array(
					'title' => $city['seoTitle'],
					'description' => $city['seoDescription'],
					'keywords' => $city['seoKeywords'],
				));
				$this->view->restitle = $city['Name'];
				$this->view->pageText = stripslashes($city['pageText']);
    		}
    		elseif (sizeof($parsedParams) == 4) {
    			if (!($region = Obj_Region::findRegion(urldecode($parsedParams[1])))) {
    				throw new Exception(_('Страница не существует'), 101);
    			}
    			if (!($city = Obj_City::findCity(urldecode($parsedParams[2])))) {
    				throw new Exception(_('Страница не существует'), 101);
    			}
    			if (!($location = Obj_Location::findLocation(urldecode($parsedParams[3])))) {
    				throw new Exception(_('Страница не существует'), 101);
    			}
    			Zend_Registry::set('LastModified', $location['Modified']);
    			Obj_Search::setBoxParam('country', $country['ID']);
    			Obj_Search::setBoxParam('region', $region['ID']);
    			Obj_Search::setBoxParam('city', $city['ID']);
    			Obj_Search::setBoxParam('location', $location['ID']);
				Zend_Registry::set('metainfo', array(
					'title' => $location['seoTitle'],
					'description' => $location['seoDescription'],
					'keywords' => $location['seoKeywords'],
				));
				$this->view->restitle = $location['Name'];
    		}
    		$this->view->currURL = HTTP_HOST.'/'.implode('/', $parsedParams).'/page';
    		$parsedParams['page'] = Zend_Registry::isRegistered('requestPage') ? Zend_Registry::get('requestPage') : (int) $this->getRequest()->getParam('page', 1);
    		$arResult = $this->getURLSearchResult($parsedParams);
    		$this->view->objects = $arResult;
    		
    	}
    	else {
    		$arParams = array(
    			'sale_type' => (int) $this->getRequest()->getParam('sale_type', OBJECT_SALE),
    			'country' => (int) $this->getRequest()->getParam('country', 0),
    			'region' => (int) $this->getRequest()->getParam('region', 0),
    			'city' => (int) $this->getRequest()->getParam('city', 0),
    			'location' => (int) $this->getRequest()->getParam('location', 0),
    			'object_type' => (int) $this->getRequest()->getParam('object_type', 0),
    			'object_price_low' => (int) $this->getRequest()->getParam('object_price_low', 0),
    			'object_price_high' => (int) $this->getRequest()->getParam('object_price_high', 1000),
    			'object_see_distance' => (int) $this->getRequest()->getParam('object_see_distance', 0),
    			'object_air_distance' => (int) $this->getRequest()->getParam('object_air_distance', 0),
    			'object_year' => (int) $this->getRequest()->getParam('object_year', 0),
    			'object_id' => (int) $this->getRequest()->getParam('object_id', 0),
    			'object_area_low' => (int) $this->getRequest()->getParam('object_area_low', 0),
    			'object_area_high' => (int) $this->getRequest()->getParam('object_area_high', 0),
    			'object_bedrooms_low' => (int) $this->getRequest()->getParam('object_bedrooms_low', 0),
    			'object_bedrooms_high' => (int) $this->getRequest()->getParam('object_bedrooms_high', 0),
    			'SwimmingPool' => (int) $this->getRequest()->getParam('SwimmingPool', 0),
    			'Security' => (int) $this->getRequest()->getParam('Security', 0),
    			'Parking' => (int) $this->getRequest()->getParam('Parking', 0),
    			'page' => (int) $this->getRequest()->getParam('page', 1),
       		);
       		$arCountry = Obj_Country::getCountry($arParams['country']);
       		if ($arCountry === false) {
       			throw new Exception(_('Страница не существует'), 101);
       		}
       		$this->loadCountryLayoutInfo($arCountry['alias']);
       		$obj = null;
       		if ($arParams['location'] != 0) {
       			$obj = Obj_Location::getLocation($arParams['location']);
				Zend_Registry::set('metainfo', array(
					'title' => $obj['seoTitle'],
					'description' => $obj['seoDescription'],
					'keywords' => $obj['seoKeywords'],
				));
       			$this->view->restitle = $obj['Name'];
       			Zend_Registry::set('LastModified', $obj['Modified']);
       		}
       		elseif ($arParams['city'] != 0) {
       			$obj = Obj_City::getCity($arParams['city']);
       			$region = Obj_Region::getRegion($arParams['region']);
    			$arLocations = Obj_Location::getLocations($obj['ID'], true);
    			$this->view->children = $arLocations;
    			$this->view->childrenLink = HTTP_HOST.'/'.$arCountry['alias'].'/'.$region['alias'].'/'.$obj['alias'].'/';
    			$this->view->childrenName = _('Районы города');
				Zend_Registry::set('metainfo', array(
					'title' => $obj['seoTitle'],
					'description' => $obj['seoDescription'],
					'keywords' => $obj['seoKeywords'],
				));
       			$this->view->restitle = $obj['Name'];
       			$this->view->pageText = stripslashes($obj['pageText']);
       			Zend_Registry::set('LastModified', $obj['Modified']);
       		}
       		elseif ($arParams['region'] != 0) {
       			$obj = Obj_Region::getRegion($arParams['region']);
    			$arCities = Obj_City::getCities($obj['ID'], true);
    			$this->view->children = $arCities;
    			$this->view->childrenLink = HTTP_HOST.'/'.$arCountry['alias'].'/'.$obj['alias'].'/';
    			$this->view->childrenName = _('Города региона');
				Zend_Registry::set('metainfo', array(
					'title' => $obj['seoTitle'],
					'description' => $obj['seoDescription'],
					'keywords' => $obj['seoKeywords'],
				));
       			$this->view->restitle = $obj['Name'];
       			Zend_Registry::set('LastModified', $obj['Modified']);
       		}
       		else {
    			$arRegions = Obj_Region::getRegions($arCountry['ID'], true);
    			$this->view->children = $arRegions;
    			$this->view->childrenLink = HTTP_HOST.'/'.$arCountry['alias'].'/';
    			$this->view->childrenName = _('Регионы');
       			$arPages = Obj_LocationContentPage::getLocationContentPages($arCountry['ID'], CONTENT_TYPE_COUNTRY);
    			if (trim($arCountry['CatalogPDF']) != '')	$arPages[] = array('href' => HTTP_HOST.'/data/'.$arCountry['CatalogPDF'], 'title' => _('Скачать каталог недвижимости'), 'target' => '_blank');
    			$this->view->pages = $arPages;
    			$this->view->restitle = $arCountry['Name'];
    			Zend_Registry::set('LastModified', $arCountry['Modified']);
    			$this->view->pageText = stripslashes($arCountry['pageText']);
       		}
       		if (!is_null($obj)) {
				Zend_Registry::set('metainfo', array(
					'title' => $obj['seoTitle'],
					'description' => $obj['seoDescription'],
					'keywords' => $obj['seoKeywords'],
				));
       		}
       		Zend_Registry::set('searchBoxParams', $arParams);
       		$arResult = Obj_Search::searchObjects($arParams);
    		$this->view->objects = $arResult;
    		$this->view->pagingLayout = 'paginationForm.phtml';
    		
    	}	
    }
    
    private function getURLSearchResult($ar) {
    	return Obj_Search::searchURLParams($ar);
    	
    }
    
    private function showCountryPage($id, $alias) {
    	$this->_helper->viewRenderer->setRender('page');
    	$arPage = Obj_LocationContentPage::findLocationContentPage($id, CONTENT_TYPE_COUNTRY, $alias);
    	if ($arPage === false) {
    		throw new Zend_Exception(_('Страница не существует'), 101);
    	}
		Zend_Registry::set('metainfo', array(
			'title' => $arPage['seoTitle'],
			'description' => $arPage['seoDescription'],
			'keywords' => $arPage['seoKeywords'],
		));
		$this->view->page = $arPage;
		Zend_Registry::set('LastModified', $arPage['Modified']);
    }
    
    private function showObject($params) {
    	$this->loadCountryLayoutInfo($params[0]);
    	$this->_helper->viewRenderer->setRender('object');
    	$arObject = Obj_Object::findObject(urldecode($params[4]), true);
    	
    	if (!$arObject && isset($params[5])) {
    		$id = str_replace('id', '', $params[5]);
    		$arObject = Obj_Object::findObject($id, true);
    	}
    	
    	if ($arObject === false) {
    		unset($params[4]);
    		$this->_redirect(HTTP_HOST.'/'.implode('/', $params));
    		return;
    	}
    	
    	Zend_Registry::set('LastModified', $arObject['Modified']);
    	
    	$arObject['Object_type'] = Obj_ObjectType::getObjectType($arObject['ObjectTypeId']);
    	
    	
  		Obj_Search::setBoxParam('country', $arObject['CountryID']);
  		Obj_Search::setBoxParam('region', $arObject['RegionID']);
  		Obj_Search::setBoxParam('city', $arObject['CityID']);
		Obj_Search::setBoxParam('location', $arObject['LocationID']);

		$objArr = Obj_Object::getFriendObjects($arObject['ID']);
		
		$this->view->sameObjects = $objArr;
    	$arObject['images'] = Obj_Image::getImages($arObject['ID']);
    	switch ($arObject['Attribute']) {
    		case OBJECT_RENT: $this->view->objtypefile = 'kutochoarenda.png'; break;
    		case OBJECT_INVESTMENT_PROJECT: $this->view->objtypefile = 'kutinvest.png'; break;
    		case OBJECT_SALE: 
    		default: $this->view->objtypefile = 'kutochoksale.png'; 
    	}
		Zend_Registry::set('metainfo', array(
			'title' => $arObject['SeoTitle'],
			'description' =>$arObject['SeoDescription'],
			'keywords' => $arObject['SeoKeywords'],
		));
    	$this->view->object = $arObject;
    	$this->view->singleObject = 1;
    }
    
    private function prepareSearchResults($ar) {
    	$result = array();
    	foreach ($ar as $v) {
    		switch ($v['ContentType']) {
    			case CONTENT_TYPE_COUNTRY:
    				$c = Obj_Country::getCountry($v['ContentID']);
    				if (!$c) continue;
    				if ($c['active'] != 1) continue;
    				$link = HTTP_HOST.'/'.$c['alias'];
    				$result[] = array('created' => $v['created'], 'quote' => $v['quote'], 'title' => $c['Name'], 'link' => $link);
    			break;
    			case CONTENT_TYPE_REGION:
    				$c = Obj_Region::getRegion($v['ContentID']);
    				if (!$c) continue;
    				if ($c['active'] != 1) continue;
    				$link = HTTP_HOST.Obj_Region::getLink($c['ID']);
    				$result[] = array('created' => $v['created'], 'quote' => $v['quote'], 'title' => $c['Name'], 'link' => $link);
    			break;
    			case CONTENT_TYPE_CITY:
    				$c = Obj_City::getCity($v['ContentID']);
    				if (!$c) continue;
    				if ($c['active'] != 1) continue;
    				$link = HTTP_HOST.Obj_City::getLink($c['ID']);
    				$result[] = array('created' => $v['created'], 'quote' => $v['quote'], 'title' => $c['Name'], 'link' => $link);
    			break;
    			case CONTENT_TYPE_LOCATION:
    				$c = Obj_Location::getLocation($v['ContentID']);
    				if (!$c) continue;
    				if ($c['active'] != 1) continue;
    				$link = HTTP_HOST.Obj_Location::getLink($c['ID']);
    				$result[] = array('created' => $v['created'], 'quote' => $v['quote'], 'title' => $c['Name'], 'link' => $link);
    			break;
    			case CONTENT_TYPE_OBJECT:
    				$c = Obj_Object::getObject($v['ContentID'], true);
    				if (!$c) continue;
    				$link = HTTP_HOST.Obj_Object::getLink($c['ID']);
    				$result[] = array('created' => $v['created'], 'quote' => $v['quote'], 'title' => $c['Name'], 'link' => $link);
    			break;
    			case CONTENT_TYPE_PAGE_CONTENT:
    				$c = Obj_LocationContentPage::getLocationContentPage($v['ContentID']);
    				if (!$c) continue;
    				if ($c['active'] != 1) continue;
    				$link = HTTP_HOST.Obj_LocationContentPage::getLink($c);
    				$result[] = array('created' => $v['created'], 'quote' => $v['quote'], 'title' => $c['Title'], 'link' => $link);
    			break;
    			case CONTENT_TYPE_NEWS:
    				$c = Obj_News::getOneNews($v['ContentID'], true);
    				if (!$c) continue;
    				$link = HTTP_HOST.'/news/'.$c['alias'];
    				$result[] = array('created' => $v['created'], 'quote' => $v['quote'], 'title' => $c['Title'], 'link' => $link);
    			break;
    			case CONTENT_TYPE_ARTICLES:
    				$c = Obj_Articles::getOneArticle($v['ContentID'], true);
    				if (!$c) continue;
    				$link = HTTP_HOST.'/articles/'.$c['alias'];
    				$result[] = array('created' => $v['created'], 'quote' => $v['quote'], 'title' => $c['Title'], 'link' => $link);
    			break;
    			case CONTENT_TYPE_SPECIAL_OFFER:
    				$c = Obj_SpecialOffer::getSpecialOffer($v['ContentID'], true);
    				if (!$c) continue;
    				$link = HTTP_HOST.'/special-offers/index/id/'.$c['ID'];
    				$result[] = array('created' => $v['created'], 'quote' => $v['quote'], 'title' => $c['Title'], 'link' => $link);
    			break;
    		}
    	}
    	return $result;
    }
    
}

